/**
 * 
 */
package com.quiz.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.quiz.model.Section;


/**
 *
 * @author Brian Boyle
 * Apr 10, 2012
 */
public class SectionDataSource extends QuizDataSource {

    /**
     * @param context
     */
    public SectionDataSource(Context context) {
        super(context);
    }

    public Section getSectionById(long sectionId) {
        String sqlQuery = "SELECT * FROM SECTION WHERE ID = ?";
        Cursor cur = getDatabase().rawQuery(sqlQuery, new String[] { String.valueOf(sectionId) });
        cur.moveToNext();
        return convertCursorToSection(cur);
    }

    public List<Section> getSections() {

        List<Section> sections = new ArrayList<Section>();
        Cursor cursor = getDatabase().query(Section.TABLE_NAME, null, null, null, null, null, null);
        cursor.moveToNext();
        while (!cursor.isAfterLast()) {
            Section section = convertCursorToSection(cursor);
            sections.add(section);
            cursor.moveToNext();
        }
        cursor.close();
        return sections;
    }

    public void updateSectionTopScore(Section section) {
        String whereClause = Section.COLUMN_ID + " = " + section.getId();
        ContentValues contentValues = new ContentValues();
        contentValues.put(Section.COLUMN_TOPSCORE, section.getTopScore());
        getDatabase().update(Section.TABLE_NAME, contentValues, whereClause, null);
    }

    public void unlockSection(long sectionId) {
        String whereClause = Section.COLUMN_ID + " = " + sectionId;
        ContentValues contentValues = new ContentValues();
        contentValues.put(Section.COLUMN_STATUS, "OPEN");
        getDatabase().update(Section.TABLE_NAME, contentValues, whereClause, null);
    }

    /**
     * @param cursor
     * @return
     */
    private Section convertCursorToSection(Cursor cur) {
        int index = 0;
        return new Section(
                cur.getLong(index++),
                cur.getString(index++),
                cur.getInt(index++),
                cur.getString(index++),
                cur.getInt(index++),
                cur.getString(index++),
                cur.getString(index++),
                cur.getInt(index++),
                cur.getInt(index++),
                cur.getInt(index++),
                cur.getInt(index++),
                cur.getInt(index++),
                cur.getInt(index++));
    }
}
